﻿package com.login;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.core.Novel;
import com.core.User;
import com.util.Datas;
import com.util.SysConstants;

public class Sever extends Thread {
	
	
	public static ServerSocket serverSocket = null;
	public ObjectOutputStream oos = null;
	public ObjectInputStream ois = null;
	public static Socket socket = null;

	public static  User user=null;
	public static  ArrayList<User> userList;
	public static  ArrayList<Novel> Novel1List;
	public static  ArrayList<Novel> Novel2List;
	
	/** 
	 *main方法
	 */
	public static void main(String[] args) throws Exception {
		serverSocket =new ServerSocket(8800);	
		int number=0;
	    while(true){
	    	 socket=serverSocket.accept();           		     
		     InetAddress ip=socket.getInetAddress();
			 System.out.println("接受到用户的ip:"+ip.getHostAddress());
		     new Sever().start();
		     number++;
		     System.out.println("接收到用户数量："+number);
	     }
		
	}
	
	

	
	@Override
	public void run() {
		try {
			oos=new ObjectOutputStream(socket.getOutputStream());
			ois=new ObjectInputStream(socket.getInputStream());	
		} catch (Exception e1) {
			
			e1.printStackTrace();
		}		
	    
		while(ois!=null){
		try {
					    	
		    	    
		    Datas datas = (Datas) ois.readObject();
		    Datas datas1 = new Datas();
	    
		    if(datas.getFlag().equals(SysConstants.SYS_LOGIN)){
		    	datas1=this.Login(datas);
		    }
		    
		    
		    else if(datas.getFlag().equals(SysConstants.SYS_REGISTER)){
		    	datas1=this.Register(datas);
		    }
		    

		    else if(datas.getFlag().equals(SysConstants.SYS_NOVELLIST)){		    	
		    	ArrayList<Novel> NovelList = new ArrayList<Novel>();		    	
		    	if(datas.getFlagList().equals(SysConstants.SYS_NOVELSTYLE1)){
					NovelList=this.WuXia();
					datas1.setNovelList(NovelList);
		    	}
		    	else{
					NovelList=this.YangQing();
					datas1.setNovelList(NovelList);
		    	}
		    	
		    }
		    
		    
		    else if(datas.getFlag().equals(SysConstants.SYS_READNOVEL)){
		    	datas1=this.readNovel(datas);
		    }
		    
		    
		    
		    else if(datas.getFlag().equals(SysConstants.SYS_DOWNLOAD)){
		    	datas1=this.downLoad(datas);
		    }
		    
		    
		    else if(datas.getFlag().equals(SysConstants.SYS_UPLOAD)){
		    	datas1=this.upLoad(datas);
		    }
		    
		    
		    oos.writeObject(datas1);
			oos.flush();
				    
		   } catch (Exception e) {			 
			  e.printStackTrace();
		   }
		}		  
		   
	}
	
	
	/**
	 * 登录操作--Login
	 */
	public Datas Login(Datas datas) throws Exception{
		String name = datas.getUser().getUserName();
		String password = datas.getUser().getUserPassword();
		User user = new User();
		
		DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
		DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc=db.parse("src/userinfo.xml");
        NodeList userinfoList=doc.getElementsByTagName("userInfo");
    	 userList=new ArrayList();
        for(int i=0;i<userinfoList.getLength();i++){
        	Node userinfoNode=userinfoList.item(i);
        	Element userinfoElement=(Element)userinfoNode;
            User userinfo=new User(userinfoElement.getAttribute("userName"),userinfoElement.getAttribute("userPassword"));
        	userList.add(userinfo);
           }
        
        int flag=0;
        for(int j=0;j<userList.size();j++){
			user=(User)userList.get(j);
			if(name.equals(user.getUserName())&&password.equals(user.getUserPassword())){
				flag=1;
				break;
			}
			else
				flag=0;
		}
        
		if(flag==1){
			datas.setFlag(SysConstants.SYS_SUCCESS);
			datas.setUser(user);
			return datas;			
		}
		
		else{
			datas.setFlag(SysConstants.SYS_ERROR);
			return datas;
		}

	}
	
	/**
	 * 注册操作--Register
	 */
	
	public Datas Register(Datas datas) throws Exception{
		String name = datas.getUser().getUserName();
		String password = datas.getUser().getUserPassword();								
		
		//读取xml里的用户信息，将其存放在userlist里，用以判断用户名是否被注册过
		DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
		DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc=db.parse("src/userinfo.xml");
        NodeList userinfoList=doc.getElementsByTagName("userInfo");
    	ArrayList userList=new ArrayList();
        for(int i=0;i<userinfoList.getLength();i++){
        	Node userinfoNode=userinfoList.item(i);
        	Element userinfoElement=(Element)userinfoNode;
            User userinfo=new User(userinfoElement.getAttribute("userName"),userinfoElement.getAttribute("userPassword"));
        	userList.add(userinfo);
           }
		
		int flag=1;
		for(int j=0;j<userList.size();j++){
			user=(User)userList.get(j);
			if(name.equals(user.getUserName())){
				flag=0;
			    break;
			}
			else flag=1;
		}
		

		if (flag == 0){
			datas.setFlag(SysConstants.SYS_ERROR);
			System.out.println("该用户名已被注册");
		}					    
		else {
			
			datas.setFlag(SysConstants.SYS_SUCCESS);
			//增加信息的元素
			Element userInfoElement = doc.createElement("userInfo");						
			userInfoElement.setAttribute("userName", name);
			userInfoElement.setAttribute("userPassword", password);
			Element userElement = (Element) doc.getElementsByTagName("user").item(0);
						
			userElement.appendChild(userInfoElement);
			
			//向xml文件里增加用户信息
			TransformerFactory transformerFactory = TransformerFactory.newInstance();						
			Transformer transformer = transformerFactory.newTransformer();						
			DOMSource domSource = new DOMSource(doc);
			transformer.setOutputProperty(OutputKeys.ENCODING,"UTF-8");						
			StreamResult result = new StreamResult(new FileOutputStream("src/userinfo.xml"));														
			transformer.transform(domSource, result);
		 }
		
		return datas;
		
	}
	
	/**
	 * 武侠小说列表
	 */


	public ArrayList<Novel> WuXia(){
	  try{
			  
	     DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
		 DocumentBuilder db = dbf .newDocumentBuilder();
		 Document doc=db.parse("src/txt_wuxia.xml");
		 

		 
	     Novel1List=new ArrayList<Novel>();
	     
	     NodeList list= doc.getElementsByTagName("txtbook");
			for(int i=0;i<list.getLength();i++){
			Element itemName=(Element)list.item(i);
			String name=itemName.getElementsByTagName("name").item(0).getFirstChild().getNodeValue();
			String description=itemName.getElementsByTagName("description").item(0).getFirstChild().getNodeValue();
			String author=itemName.getElementsByTagName("author").item(0).getFirstChild().getNodeValue();    	

	        		Novel novel=new Novel( name, author, description);
	        		Novel1List.add(novel);

	        	 }	        
	         }catch(Exception e){
		          e.printStackTrace();			 
		  }			  
		    return Novel1List;
		 
	 }
	
	/**
	 * 言情小说列表
	 */
	public ArrayList<Novel> YangQing(){
		  try{   
			  //构建Dom树
			     DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
				 DocumentBuilder db = dbf .newDocumentBuilder();
				 Document doc=db.parse("src/txt_yanqing.xml");

			     Novel2List=new ArrayList<Novel>();
			     
			     NodeList list= doc.getElementsByTagName("txtbook");
					for(int i=0;i<list.getLength();i++){
					Element itemName=(Element)list.item(i);
					String name=itemName.getElementsByTagName("name").item(0).getFirstChild().getNodeValue();
					String description=itemName.getElementsByTagName("description").item(0).getFirstChild().getNodeValue();
					String author=itemName.getElementsByTagName("author").item(0).getFirstChild().getNodeValue();

			        			Novel novel=new Novel( name, author, description);
			        			Novel2List.add(novel);

			        		}
			        	 }
				 catch(Exception e){
					 e.printStackTrace();
				 }
		  return Novel2List;
		 
	 }  
	
	/**
	 * 读小说
	 */
	public Datas readNovel(Datas datas) throws Exception{

		BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream("d:/小说/"+datas.getNovel().getName()+".txt"),"GBK"));
			String str="";
			for(int i=0;i<2;i++){
				str=str+br.readLine();
			}
			datas.setTXTContents(str);
			
		
		return datas;
	}
	
	/**
	 * 下载小说
	 */
	public Datas downLoad(Datas datas) throws Exception{
		
		FileReader fr=null;
		fr=new FileReader("d:/小说/"+datas.getNovel().getName()+".txt");				 																				
		BufferedReader br = new BufferedReader(fr);
		String str = br.readLine();
		String str1="";
		while ((str1 = br.readLine()) != null)
			   str += str1;
		datas.setTXTContents(str);
		
		br.close();
		fr.close();
		return datas;
	}
	
	/**
	 * 上传小说
	 */
	public Datas upLoad(Datas datas) throws Exception{
		
		FileWriter fw = new FileWriter("d:/小说/"+datas.getNovel().getName()+".txt");
		System.out.println(new Novel().getName());
		BufferedWriter bw = new BufferedWriter(fw);
		bw.write(datas.getTXTContents());
		bw.flush();
		
		FileReader fr = new FileReader("d:/小说/"+datas.getNovel().getName()+".txt");																								
		BufferedReader br = new BufferedReader(fr);
		if (br.readLine() != null)
			datas.setFlag(SysConstants.SYS_SUCCESS);
		bw.close();
		fw.close();
		br.close();
		fr.close();
		
		
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document doc3 = db.parse("src/txt_wuxia.xml");
			
			if (datas.getFlagList().equals(SysConstants.SYS_NOVELSTYLE1)) {

				Element brandElement= doc3.createElement("txtbook");
				//书名
				Element nameElement=doc3.createElement("name");
				org.w3c.dom.Text text1=doc3.createTextNode(((Novel) datas.getNovelList().get(0)).getName());
				nameElement.appendChild(text1);
				//简介 
				Element descriptionElement=doc3.createElement("description");
				org.w3c.dom.Text text2=doc3.createTextNode(((Novel) datas.getNovelList().get(0)).getDescription());
				descriptionElement.appendChild(text2);
				//作者
				Element authorElement=doc3.createElement("author");
				org.w3c.dom.Text text3=doc3.createTextNode(((Novel) datas.getNovelList().get(0)).getAuthor());
				authorElement.appendChild(text3);
				
				//获得父节点wuxialist
				Element wuxialist= (Element) doc3.getElementsByTagName("wuxialist").item(0);
				brandElement.appendChild(nameElement);
				brandElement.appendChild(descriptionElement);
				brandElement.appendChild(authorElement);
				wuxialist.appendChild(brandElement);
				
			} 
			else if (datas.getFlagList().equals(SysConstants.SYS_NOVELSTYLE1)){
					 
				Element lovenovelElement = (Element) doc3.getElementsByTagName("yanqinglist").item(0);						
				Element LovenovelElement = doc3.createElement("txtbook");						
				LovenovelElement.setAttribute("name",((Novel) datas.getNovelList().get(0)).getName());														
				LovenovelElement.setAttribute("author",((Novel) datas.getNovelList().get(0)).getAuthor());														
				LovenovelElement.setAttribute("description",((Novel) datas.getNovelList().get(0)).getDescription());
														
				lovenovelElement.appendChild(LovenovelElement);
			}
			
			//保存XML文件
			TransformerFactory transformerFactory = TransformerFactory.newInstance();					
			Transformer transformer = transformerFactory.newTransformer();					
			DOMSource domSource = new DOMSource(doc3);
			transformer.setOutputProperty(OutputKeys.ENCODING,"UTF-8");					
			StreamResult result = new StreamResult(new FileOutputStream("src/txt_wuxia.xml"));												
			transformer.transform(domSource, result);
			
			return datas;
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
}
        